////
////  SchemeProgramView.swift
////  vr_web
////
////  Created by 李旭峰 on 2020/7/13.
////
//
//import UIKit
//import WebKit
//import RxSwift
//import RxCocoa
//import FCUUID
//@objc protocol SchemeProgramViewDelegate {
//    @objc func routeToDecorateDetail(with schemeId:String,workId:String?,hotspots:[String:Any]?)
//    @objc func onGoBack(_ params:String)
//    @objc func getTrtcAuthInfo()
//    @objc func notifyDesignerJoined()
//    @objc func switchToDesignerShopView(_ designerId:String)
//}
//class SchemeProgramView: UIView {
//    var url:URL?
//    private var schemeId:String?
////    private var roomId:String?
//    private var vrType:Int?
//    weak var delegate:SchemeProgramViewDelegate?
//    var isNeedGoBack:Bool = true
//    var isNeedPopToRoot:Bool = false
//    var isNeedRightBarItem:Bool = false
//    let maskImageView = UIImageView(image: UIImage(named: "image_vrbg"))
//    let contentView = UIView()
//    var shareBaseUrl:String = ""
//    var tenantId:String = ""
//    var userId:String = "0"
//    lazy var webView:WKWebView = {
//        let config = WKWebViewConfiguration()
//        config.preferences.minimumFontSize = 9.0
//        var webView = WKWebView(frame: CGRect.zero, configuration: config)
//        webView.uiDelegate = self
//        webView.navigationDelegate = self
//        return webView
//    }()
//    let videoViewModel:AsmanVideoRecordViewModel = AsmanVideoRecordViewModel()
//    lazy var bridge:WKWebViewJavascriptBridge = {
//        let tempBridge = WKWebViewJavascriptBridge(for: self.webView)!
//        return tempBridge
//    }()
//
//    init(withUrl url:URL?) {
//        self.url = url
//        super.init(frame: CGRect.zero)
//        AsmanLiteManager.default.delegate = self
//        self.loadView()
//        self.viewDidLoad()
//    }
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
//    
//    func loadView(){
//        self.webView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight + 20)
//        self.maskImageView.frame = UIScreen.main.bounds
//        self.maskImageView.contentMode = .scaleToFill
//        self.maskImageView.layer.masksToBounds = true
//        self.contentView.backgroundColor = UIColor.purple
//        self.contentView.frame = UIScreen.main.bounds
//        self.addSubview(self.contentView)
//        self.addSubview(self.maskImageView)
//        self.contentView.addSubview(self.webView)
//    }
//    
//    func viewDidLoad(){
//        if let tempUrl = self.url {
//            self.resetUrlPath(tempUrl)
//        }
//    }
//    func viewWillAppear(){
//    }
//    func viewDidAppear(){
//        
//    }
//    func viewWillDisappear(){
//        
//    }
//    func viewDidDisappear(){
//        
//    }
//    deinit {
//        print("scheme program view did deinit")
////        AsmanLiteManager.default.delegate = nil
////        if AsmanLiteManager.default.rtcStatus != .kInvalid {
////            AsmanLiteManager.default.exitRoom(withRoomId: self.roomIdStr, andCallBack: nil)
////        }
////        AsmanLiteManager.default.deinitRtcRoom()
//    }
//    
//    func resetUrlPath(_ url:URL){
//        DispatchQueue.main.async {
//            self.url = url
//            self.maskImageView.alpha = 1.0
//            self.maskImageView.isHidden = false
//            let config = WKWebViewConfiguration()
//            config.preferences.minimumFontSize = 9.0
//            let webView = WKWebView(frame: CGRect.zero, configuration: config)
//            self.resetWebView(newWebView: webView)
//            
//            self.webView.evaluateJavaScript("navigator.userAgent", completionHandler: {[weak self] (idresult, error) in
//                guard let `self` = self else { return }
//                print("设置之前 - user agent : \(idresult as? String ?? "")")
//                var tempUserAgent = idresult as? String ?? ""
//                let infoDictionary = Bundle.main.infoDictionary
//                let majorVersion:String = String.SwitchToString(infoDictionary?["CFBundleShortVersionString"]) ?? ""
//                let identifierString = "xiaoniuge"
//                if let range = tempUserAgent.range(of: identifierString) {
//                    let location = tempUserAgent.distance(from: tempUserAgent.startIndex, to: range.lowerBound) - 1
//                    tempUserAgent = String(tempUserAgent.prefix(location))
//                }
//                tempUserAgent += " \(identifierString)/\(majorVersion)"
//                UserDefaults.standard.register(defaults: ["UserAgent":tempUserAgent])
//                let config = WKWebViewConfiguration()
//                config.preferences.minimumFontSize = 9.0
//                let webView = WKWebView(frame: UIScreen.main.bounds, configuration: config)
//                self.resetWebView(newWebView: webView)
//                self.initBridge()
//                self.webView.evaluateJavaScript("navigator.userAgent", completionHandler: {[weak self] (newIdresult, error) in
//                    dPrintLog("设置之后 - user agent : \(newIdresult as? String ?? "")")
//                })
//                DispatchQueue.main.async {
//                    if let tempUrl = self.url {
//                        let request = URLRequest(url: tempUrl)
//                        self.webView.load(request)
//                    }
//                }
//            })
//        }
//    }
//    func resetWebView(newWebView:WKWebView){
//        let oldWebView = self.webView
//        oldWebView.uiDelegate = nil
//        oldWebView.navigationDelegate = nil
//        oldWebView.removeFromSuperview()
//        
//        self.webView = newWebView
//        self.webView.uiDelegate = self
//        self.webView.navigationDelegate = self
//        self.webView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight + 20)
//        self.contentView.addSubview(self.webView)
////        if #available(iOS 11.0, *) {
////            self.webView.scrollView.contentInsetAdjustmentBehavior = .never
////        } else {
////            self.edgesForExtendedLayout = .all
////        }
//    }
//    func initBridge(){
//        self.bridge = WKWebViewJavascriptBridge(for: self.webView)!
//        self.bridge.setWebViewDelegate(self)
//    }
//    private func registerJSHandler(){
//        self.bridge.registerHandler("getVersion") { (params, callBack) in
//            var result:[String:Any] = [:]
//            result["code"] = "10000"
//            result["result"] = UIDevice.current.appVersion
//            callBack?(result)
//        }
//        // 唤起原生应用的分享
//        self.bridge.registerHandler("showSharePageView") {[weak self] (params, callBack) in
//            let callBackParams:[String:Any] = ["code":"10000"]
//            callBack?((callBackParams as NSDictionary).jsonString())
//        }
//        // 直接调起微信分享
//        self.bridge.registerHandler("shareWXMiniProgram") {[weak self] (params, callBack) in
//            let callBackParams:[String:Any] = ["code":"10000"]
//            callBack?((callBackParams as NSDictionary).jsonString())
//        }
//        // 调用原生应用的后退事件，无需参数。如果历史记录不为空则后退，如果历史记录为空，则关闭当前webview。
//        self.bridge.registerHandler("goBack") {[weak self] (params, callBack) in
//            guard let `self` = self else { return }
//            if self.isNeedGoBack && self.webView.canGoBack {
//                self.webView.goBack()
//            }else{
//                
//                self.delegate?.onGoBack("")
//            }
//            let callBackParams:[String:Any] = ["code":"10000"]
//            callBack?((callBackParams as NSDictionary).jsonString())
//        }
//        // 关闭webview，无需参数
//        self.bridge.registerHandler("closeNativeView") {[weak self] (params, callBack) in
//            guard let `self` = self else { return }
//            self.delegate?.onGoBack("")
//            let callBackParams:[String:Any] = ["code":"10000"]
//            callBack?((callBackParams as NSDictionary).jsonString())
//        }
//        // 弹出登陆页
//        self.bridge.registerHandler("showLoginView") {[weak self] (params, callBack) in
//            let callBackParams:[String:Any] = ["code":"10000"]
//            callBack?((callBackParams as NSDictionary).jsonString())
//        }
//        self.bridge.registerHandler("switchToDesignerShopView") {[weak self] (params, callBack) in
//            guard let `self` = self else { return }
//            //TODO: 显示设计师主页
//            guard let tempParams = params as? [String:Any], let designerId = String.SwitchToString(tempParams["designerId"]) else {
//                let callBackParams:[String:Any] = ["code":"-10000","msg":"缺少设计师ID"]
//                callBack?((callBackParams as NSDictionary).jsonString())
//                return
//            }
//            self.delegate?.switchToDesignerShopView(designerId)
//            let callBackParams:[String:Any] = ["code":"10000"]
//            callBack?((callBackParams as NSDictionary).jsonString())
//        }
//        // 报价单页
//        self.bridge.registerHandler("switchToQuotationView") {[weak self] (params, callBack) in
//            guard let `self` = self else { return }
//            guard let tempParams = params as? [String:Any], let decorationInfo = tempParams["decorationInfo"] as? [String:Any] else {
//                //TODO: 缺少参数，通知flutter
//                let callBackParams:[String:Any] = ["code":"-10000","msg":"缺少方案ID"]
//                callBack?((callBackParams as NSDictionary).jsonString())
//                return
//            }
//            guard let schemeId = String.SwitchToString(decorationInfo["schemeId"]) else {
//                //TODO: 缺少参数，通知flutter
//                let callBackParams:[String:Any] = ["code":"-10000","msg":"缺少方案ID"]
//                callBack?((callBackParams as NSDictionary).jsonString())
//                return
//            }
//            let hotspots = decorationInfo["hotspots"] as? [String:Any] ?? [:]
//            let workId = String.SwitchToString(decorationInfo["workId"])
//            self.delegate?.routeToDecorateDetail(with: schemeId, workId: workId, hotspots: hotspots)
//            let callBackParams:[String:Any] = ["code":"10000"]
//            callBack?((callBackParams as NSDictionary).jsonString())
//        }
//        self.bridge.registerHandler("nativationToGoodsDetail") {[weak self] (params, callBack) in
//            guard let _ = self else { return }
//            //TODO: 显示商品详情页
//            DispatchQueue.main.async{
//                let callBackParams:[String:Any] = ["code":"10000"]
//                callBack?((callBackParams as NSDictionary).jsonString())
//            }
//        }
//        // 腾讯云事件
//        self.bridge.registerHandler("callAppTrtc") {[weak self] (jsParams, callBack) in
//            DispatchQueue.main.async {
//                guard let `self` = self else { return }
//                guard let `jsParams` = jsParams as? [String:Any] else {
//                    callBack?(["code":"-10000","result":false,"msg":"参数缺失"])
//                    return
//                }
//                guard let actionType = String.SwitchToString(jsParams["type"]) else {
//                    callBack?(["code":"-10000","result":false,"msg":"参数缺失"])
//                    return
//                }
//                switch actionType {
//                case "joinRoom":
//                    DeviceAuthorizationUtil.audioAuthorization({[weak self] in
//                        guard let `self` = self else { return }
//                        //TODO: sdkAppId 和 userSig 由js提供参数
//                        switch AsmanLiteManager.default.rtcStatus {
//                        case .kInvalid:
//                            let url = self.url
//                            let urlParams = url?.absoluteString.cx_urlQueryDict() ?? [:]
//                            let schemeId = String.SwitchToString(urlParams["schemeId"]) ?? ""
//                            //TODO: sdkAppId 和 userSig 由js提供参数
//                            let liteInfo = jsParams["params"] as? [String : Any]
//                            if liteInfo == nil {
//                                callBack?(["code":"-3316","result":false,"msg":"参数缺失"])
//                                return
//                            }
//                            guard let userId = String.SwitchToString(liteInfo!["userId"]),
//                                let roomId = String.SwitchToString(liteInfo!["roomId"])?.decimal.uint32Value,
//                                let userSig = String.SwitchToString(liteInfo!["userSig"]),
//                                let sdkAppId = String.SwitchToString(liteInfo!["sdkAppId"])?.decimal.uint32Value
//                                else {
//                                callBack?(["code":"-3316","result":false,"msg":"参数缺失"])
//                                return
//                            }
//                            AsmanLiteManager.default.initRtcRoom2(withRoomId: roomId, schemeId: schemeId, params: [:]) { (success, error, code) in
//                                if !success {
//                                    callBack?(["code":"-10000","result":false,"msg":"加入房间异常"])
//                                    return
//                                }
//                                AsmanLiteManager.default.enterRoom(sdkAppId: sdkAppId, userSig: userSig, userId: userId, roomId: roomId) {[weak self] (success, error, errorCode) in
//                                    guard let `self` = self else { return }
//                                    if success {
//                                        callBack?(["code":"10000","result":true,"msg":""])
//                                    }else {
//                                        callBack?(["code":String.SwitchToString(errorCode) ?? "-10000","result":false,"msg":""])
//                                    }
//                                }
//                            }
//                        case .kDidInit,.kDidEnter:
//                            callBack?(["code":"10000","result":true,"msg":""])
//                            if AsmanLiteManager.default.isUserJoinRoom {
//                                let userId = self.userId
//                                self.onRemoteUserEnterRoom(userId)
//                            }
//                        default:break
//                        }
//                    }) { (isFirst) in
//                        if isFirst {
//                            let callBackParams:[String:Any] = ["code":"-10000","result":false,"msg":"麦克风权限获取失败"]
//                            callBack?((callBackParams as NSDictionary).jsonString())
//                        }else {
//                            //TODO: 弹出去设置权限弹窗
//                            let alertController = UIAlertController(title: "", message: "请在iPhone的“设置-隐私-麦克风”选项中，允许牛牛搭访问你的手机麦克风。", preferredStyle: .alert)
//                            let cancelAction = UIAlertAction(title: "好的", style:.cancel) { (_) in }
//                            let sureAction = UIAlertAction(title: "设置", style: .default) { (action) in
//                                if let tempOpenUrl = URL(string: UIApplication.openSettingsURLString) {
//                                    DispatchQueue.main.async {
//                                        UIApplication.shared.open(tempOpenUrl, options: [:]) { (granted) in }
//                                    }
//                                }
//                            }
//                            alertController.addAction(cancelAction)
//                            alertController.addAction(sureAction)
//                            UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
//                            let callBackParams:[String:Any] = ["code":"-10000","result":false,"msg":"用户未授权"]
//                            callBack?((callBackParams as NSDictionary).jsonString())
//                            return
//                        }
//                    }
//                case "leaveRoom":
//                    AsmanLiteManager.default.exitRoom(withCallBack: nil)
//                    callBack?(["code":"10000","result":true,"msg":""])
//                    AsmanLiteManager.default.deinitRtcRoom()
//                default:break
//                }
//            }
//            }
//    }
//    private func eveJsCode(params:[String:Any]){
//        self.bridge.callHandler("notifyTrtcH5", data: params) { (response) in }
//    }
//    
//    private func onJoinRoom(jsParams:[String:Any],callBack:WVJBResponseCallback?){
//        
//    }
//}
//
//extension SchemeProgramView : WKUIDelegate, WKNavigationDelegate{
//    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
//        dPrintLog("SchemeWebView", "decide policy")
//        decisionHandler(.allow)
//    }
//    /// 页面开始加载时调用
//    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
//        dPrintLog("SchemeWebView", "did start provisional")
//    }
//    /// 页面内容开始返回时调用
//    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
//        dPrintLog("SchemeWebView", "did commit")
//    }
//    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
//        self.resetUrlPath(self.url!)
//        dPrintLog("SchemeWebView", "did fail provisional")
//    }
//    /// 页面加载完成后调用
//    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
//        dPrintLog("SchemeWebView", "did finish")
//        UIView.animate(withDuration: 2, delay: 0.5, options: [], animations: {
//            self.maskImageView.alpha = 0
//        }) { (isFinished) in
//            self.maskImageView.isHidden = true
//        }
//        self.registerJSHandler()
//        webView.evaluateJavaScript("document.readyState") {[weak self] (response, error) in
//            guard let `self` = self else { return }
//            if response != nil {
//                self.webView.evaluateJavaScript("document.body.scrollHeight") { (height, error) in
//                    self.webView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight + 20)
//                }
//            }
//        }
//    }
//    /// 页面加载失败时调用
//    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
//        dPrintLog("SchemeWebView", "did fail")
//    }
//    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
//        let alertViewController = UIAlertController(title: "", message: message, preferredStyle: .alert)
//        let cancelAction = UIAlertAction(title: "确定", style: .cancel) { (alertAction) in
//            completionHandler()
//        }
//        alertViewController.addAction(cancelAction)
//        UIApplication.shared.keyWindow?.rootViewController?.present(alertViewController, animated: true, completion: nil)
//    }
//    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
//        let alertViewController = UIAlertController(title: "", message: message, preferredStyle: .alert)
//        let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (alertAction) in
//            completionHandler(false)
//        }
//        let sureAction = UIAlertAction(title: "确定", style: .default) { (alertAction) in
//            completionHandler(true)
//        }
//        alertViewController.addAction(cancelAction)
//        alertViewController.addAction(sureAction)
//        UIApplication.shared.keyWindow?.rootViewController?.present(alertViewController, animated: true, completion: nil)
//    }
//    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
//        let alertController = UIAlertController(title: prompt, message: "", preferredStyle: .alert)
//        alertController.addTextField { (textfield) in
//            textfield.text = defaultText
//        }
//        alertController.addAction(UIAlertAction(title: "完成", style: .default, handler: { (alertAction) in
//            completionHandler(alertController.textFields?.first?.text)
//        }))
//        UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
//    }
//}
//
//extension SchemeProgramView : AsmanLiteDelegate {
//    func onUserEnterRoom(){
//        dPrintLog("TRTC - 自己进入房间")
//        //AsmanLiteManager.default.rtcAnswer()
//    }
//    func onUserLeaveRoom(){
//        AsmanLiteManager.default.deinitRtcRoom()
//    }
//    func onRemoteUserEnterRoom(_ userId: String){
//        // {"type":"onRemoteUserLeaveRoom","params":{}}
//        var params:[String:Any] = [:]
//        params["type"] = "onRemoteUserEnterRoom"
//        params["params"] = ["userId":userId]
//        self.eveJsCode(params: params)
//    }
//    func onRemoteUserLeaveRoom(_ userId: String, reason: Int){
//        var params:[String:Any] = [:]
//        params["type"] = "onRemoteUserLeaveRoom"
//        params["params"] = ["userId":userId]
//        self.eveJsCode(params: params)
//    }
//}
